#!/bin/bash

source ~/etc/cs_config

CS_BASE=$1

echo CASTEP server on host $CS_HOST in directory $CS_HOME is `$CS_RSH $CS_HOST $CS_HOME/bin/status`

if ! $CS_RSH $CS_HOST $CS_HOME/bin/status > /dev/null ; then
    echo Server is currently down, trying to restart it...
    cs_start
    while ! $CS_RSH $CS_HOST $CS_HOME/bin/status > /dev/null; do
	sleep 10
    done
fi

JOB_ID=`$CS_RSH $CS_HOST $CS_HOME/bin/get_new_job_id`

$CS_RSH $CS_HOST mkdir $CS_HOME/$JOB_ID
echo Copying files to $CS_HOST...
$CS_RCP ${CS_BASE}.cell $CS_HOST:$CS_HOME/$JOB_ID/job.cell
$CS_RCP ${CS_BASE}.param $CS_HOST:$CS_HOME/$JOB_ID/job.param
$CS_RCP *.usp $CS_HOST:$CS_HOME/$JOB_ID

$CS_RSH $CS_HOST "$CS_HOME/bin/qsubw $JOB_ID" || (echo "Error submitting job"; exit 1)

JOB_STATUS=`$CS_RSH $CS_HOST $CS_HOME/bin/get_job_status $JOB_ID`

if [[ $JOB_STATUS == "KILLED" ]]; then
    echo Job killed
    exit 1
fi

if [[ $JOB_STATUS == "ERROR" ]]; then
    echo Error when running job
    $CS_RCP $CS_HOST:$CS_HOME/$JOB_ID/run.castep ./$CS_BASE.castep
    $CS_RCP $CS_HOST:$CS_HOME/$JOB_ID/run.*.err .
    exit 1
fi

if [[ $JOB_STATUS == "TIMEOUT" ]]; then
    echo Ran out of time running job
    exit 1
fi

if [[ $JOB_STATUS == "SUCCESS" ]]; then
    echo Job finished successfully
    $CS_RCP $CS_HOST:$CS_HOME/$JOB_ID/run.castep ./$CS_BASE.castep
    exit 0
fi

